#! /usr/bin/python
# encoding=utf-8
# Created by Fenglu Niu on 2025/5/12 9:27
import base64
import json
import os
from io import BytesIO
from typing import List

from dotenv import load_dotenv
from pydub import AudioSegment
from tencentcloud.common import credential
from tencentcloud.tts.v20190823 import models, tts_client

from common import agent_voice_type
from common.snowflake import Snowflake


class TencentTTSApi(object):
    __instance = None
    __is_first = True

    def __new__(cls):
        if not cls.__instance:
            cls.__instance = object.__new__(cls)
        return cls.__instance

    def __init__(self):
        if TencentTTSApi.__is_first:
            TencentTTSApi.__is_first = False
            load_dotenv()
            self.__secret_id = os.getenv('TENCENT_SECRET_ID')
            self.__secret_key = os.getenv('TENCENT_SECRET_KEY')


    def tts(self, text: str, agents: List[int]):
        cred = credential.Credential(self.__secret_id, self.__secret_key)
        client = tts_client.TtsClient(cred, "")
        req = models.TextToVoiceRequest()
        agent =  agents[0] if len(agents) == 1 else 0
        params = {
            'SessionId': str(Snowflake(datacenter_id=2, worker_id=1).get_id()),
            'VoiceType': agent_voice_type[agent],
            'Codec': 'mp3',
            'Text': text
        }
        req.from_json_string(json.dumps(params))
        # 返回的resp是一个TextToVoiceResponse的实例，与请求对象对应
        resp = client.TextToVoice(req)
        duration = self._voice_duration(resp.Audio)
        return {'audio': resp.Audio, 'duration': duration}

    @staticmethod
    def _voice_duration(audio_base64: str):
        # 解码 Base64 数据为二进制数据
        audio_data = base64.b64decode(audio_base64)
        # 将二进制数据转换为 AudioSegment 对象
        audio_segment = AudioSegment.from_file(BytesIO(audio_data))
        # 获取音频时长（单位为毫秒）
        duration_ms = len(audio_segment)
        # 转换为秒
        duration_s = duration_ms // 1000
        return duration_s


if __name__ == '__main__':
    tts_api = TencentTTSApi()
    result = tts_api.tts("你好,我是润宝，润物细无声", [5])

    with open("test.mp3", "wb") as f:
        f.write(base64.b64decode(result.get('audio')))
